<template>
  <div>
    localStorage store
  </div>
  <div>count:{{count}}</div>
  <button @click="incrementCount">count+1</button>
</template>
<script setup lang="ts">
import {onMounted} from 'vue'
import {storeToRefs} from 'pinia'
import {useCounterStore} from '@/stores/counter'
const counterStore = useCounterStore()
counterStore.$subscribe((mutation,state) => {
  console.log('$subscribe-mutation-state',mutation,state)
  localStorage.setItem('counter',JSON.stringify(state))
})
const {count} = storeToRefs(counterStore)
function incrementCount(){
  count.value = count.value + 1
}
onMounted(() => {
  const store = JSON.parse(localStorage.getItem('counter') as string)
  console.log('mounted-store=',store)
  if(store){
    // 无效
    // counterStore.$patch((state) => {
    //   state = store
    // })
    counterStore.$patch({...store})
  }
})
// 也可以监听pinia实例上的所有的store变化
// import {watch} from 'vue'
// import {createPinia} from 'pinia'
// const pinia = createPinia()
// watch(pinia.state,(state)=>{
//   // 每当状态变化，将所有的store持久化到本地存储
//   localStorage.setItem('piniaState',JSON.stringify(state))
// },{deep:true})
</script>